
import api from '../../utils/api'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    actinfo:'',
    actid:'',
    act_location:'',
    rangflag:0,
    authflag:false
  },

  callsetback(e){
    console.log(e)
    if( e.detail.authSetting['scope.userLocation'] ){
      this.setData({authflag:false})
      this.getlocation()
    }
  },

  gopage(){
    let _this = this
   if( app.globalData.dingweiflag==false){
      Toast('定位失败，请检查设置')
      return
   }
   
   if( this.data.rangflag == 0 ){
      Dialog.confirm({
        title: '提示信息',
        message: '当前位置不在签到的范围内，是否继续签到？',
        confirmButtonText:'签到'
      }).then(() => {
        console.log('confirm')
        // on confirm
        _this.gourl()
      }).catch(()=>{})
   }else{
    _this.gourl()
   }
  },
  async gourl(){
    if( app.globalData.unionid=='osA0J65tmkVpMa-iQ6rVyd7TeMHA'){
      wx.showModal({
        title: '提示',
        content: '准备发送',
        success (res) {}
      })
    }
    let data={}
    data['flag'] = 'saoma_qdinfo'
    data['activityid'] = this.data.actid
    data['do_type'] = this.data.actinfo.do_type
    data['member_type'] = 0
    data['userid'] = this.data.actinfo.userid
    data['is_range'] = this.data.rangflag
    data['lat'] = app.globalData.currpoint.latitude
    data['lng'] = app.globalData.currpoint.longitude

    if( app.globalData.unionid=='osA0J65tmkVpMa-iQ6rVyd7TeMHA'){
      let s = JSON.stringify(data)
      wx.showModal({
        title: '提示',
        content: s,
        success (res) {}
      })
    }

    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      result['recode'] = recode
      api.setStore('qdresult',result)
      wx.redirectTo({
        url:'/pages/index_active_sign_success/index'
      })
    }else {
      Toast.fail(message)
      /*api.setStore('qdresult',{'recode':'FAIL','message':message,'active_label':message})
      wx.redirectTo({
        url:'/pages/index_active_sign_success/index'
      })
      */
    }
  },

  //获取活动详情
  async getDetail(activityid){
    let _this = this
    let data={}
    data['flag'] = 'saoma_qd'
    data['activityid'] = activityid
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      this.setData({
        actinfo:result
      })
      if( result.status>1 ){
        Dialog.alert({
          title: '提示',
          message: '您已经签到成功',
        }).then(() => {
          // on close
          wx.redirectTo({
            url: '/pages/index_active_evaluation/index?id='+activityid,
          })
        });
      }
    }else {
      console.log(message)
      // Toast(message)
      Dialog.alert({
        title: '提示',
        message: message,
      }).then(() => {
        // on close
        wx.reLaunch({
          url: '/pages/index/index',
        })
      });
    }
  },

  //获取定位
  async getActLoc(activityid){
    let _this = this
    let data={}
    data['flag'] = 'v2qnzj_qt_loct'
    data['activityid'] = activityid
    const {recode, result, message} = await api.send(data)
    if(recode === 'SUCC') {
      _this.setData({
        act_location:result||{}
      })
      let range = result.range||0
      if( range ){
        let dis = _this.GetDistance(result.lat,result.lng,app.globalData.currpoint.latitude,app.globalData.currpoint.longitude)
        console.log(dis)
        if (dis >range){
           _this.setData({rangflag:0})
        }else {
          _this.setData({rangflag:1})
        }
      }
    }else {
      Toast(message)
    }
  },

  GetDistance( lat1,  lng1,  lat2,  lng2){
      var radLat1 = lat1*Math.PI / 180.0;
      var radLat2 = lat2*Math.PI / 180.0;
      var a = radLat1 - radLat2;
      var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
          Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
      s = s *6378.137 ;// EARTH_RADIUS;
      s = Math.round(s * 10000)/10;
      return parseInt(s);
  },

  getlocation(){
    let actid = this.data.actid
    let _this = this;
    _this.setData({authflag:false})
    wx.getSetting({
      success: res => {
        console.log(res)
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success () {
              api.getloc(()=>{
                _this.getActLoc(actid)
              },()=>{
                _this.getActLoc(actid)
              })
            },
            fail(res){
              console.log(res)
              app.globalData.dingweiflag = false
              _this.setData({authflag:true})
            }
          })
        }else{
          api.getloc(()=>{
            _this.getActLoc(actid)
          },()=>{
            _this.getActLoc(actid)
          })
        }
      },
      fail: error => {
        console.log(error);
        app.globalData.dingweiflag = false
        _this.getActLoc(actid)
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let id = options.id||''
    if( options.scene ){
      let obj = api.decodeurl(options.scene)
      if( obj ) id = obj.id||''
    }

    let gourl = '/pages/login/index?url='+encodeURIComponent('/pages/index_active_sign/index?id='+id)
    if( !api.isauth() ){
      wx.navigateTo({
        url: gourl
      })
      return
    }

    this.setData({actid:id})
    this.getDetail(id)
    this.getlocation()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})